package com.ruizhong.centercontroll.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruizhong.centercontroll.dao.TTextViewMapper;
import com.ruizhong.centercontroll.entity.TCommand;
import com.ruizhong.centercontroll.entity.TSwitch;
import com.ruizhong.centercontroll.entity.TTextView;
import com.ruizhong.centercontroll.service.TCommandService;
import com.ruizhong.centercontroll.service.TTextViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class TTextViewServiceImpl extends ServiceImpl<TTextViewMapper, TTextView> implements TTextViewService {
    @Override
    @Transactional
    public void saveNewTextList(List<Map<String, Object>> textList, Integer pageId, boolean isNew) {
        deleteTextViewsByPageId(pageId);
        final HashMap<Integer, List<Map<String, Object>>> textViewIdMapInitCommandList = new HashMap<>();
        textList.forEach(textViewOB -> {
            Object textValue = textViewOB.get("textValue");
            Object traditionalTextValue = textViewOB.get("traditionalTextValue");
            Object englishTextValue = textViewOB.get("englishTextValue");
            Object fontColor = textViewOB.get("fontColor");
            Object fontSize = textViewOB.get("fontSize");
            TTextView tTextView = new TTextView();
            tTextView.setPageId(pageId);
            tTextView.setTextValue(textValue == null ? null : textValue.toString());
            tTextView.setTraditionalTextValue(traditionalTextValue == null ? null : traditionalTextValue.toString());
            tTextView.setEnglishTextValue(englishTextValue == null ? null : englishTextValue.toString());
            tTextView.setW(Double.parseDouble(textViewOB.get("w").toString()));
            tTextView.setH(Double.parseDouble(textViewOB.get("h").toString()));
            tTextView.setX(textViewOB.get("x") == null ? 0 : Double.parseDouble(textViewOB.get("x").toString()));
            tTextView.setY(textViewOB.get("y") == null ? 0 : Double.parseDouble(textViewOB.get("y").toString()));
            tTextView.setZ(Integer.parseInt(textViewOB.get("z").toString()));
            tTextView.setFontColor(fontColor == null ? null : fontColor.toString());
            tTextView.setFontSize(fontSize == null ? null : Integer.parseInt(fontSize.toString()));
            Object displayVariableName = textViewOB.get("displayVariableName");
            Object displayVariableValue = textViewOB.get("displayVariableValue");
            tTextView.setDisplayVariableName(displayVariableName == null ? null : displayVariableName.toString());
            tTextView.setDisplayVariableValue(displayVariableValue == null ? null : displayVariableValue.toString());
            Object conditionShow = textViewOB.get("conditionShow");
            tTextView.setConditionShowData(conditionShow == null ? null : (Boolean) conditionShow ? 1 : 0);
            List<Map<String, Object>> initCommandList = null;
            Map logicGraph = (Map) textViewOB.get("logicGraph");
            if (!isNew) {
                initCommandList = (List<Map<String, Object>>) textViewOB.get("initCommandList");
            } else {
                ObjectMapper mapper = new ObjectMapper();
                try {
                    String logicGraphString = mapper.writeValueAsString(logicGraph);
                    tTextView.setLogicGraphData(logicGraphString);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                Map<String, List> typeMapCommandList = TCommandServiceImpl.getCommandsByGraph(logicGraph);
                initCommandList = typeMapCommandList.get("initCommandList");
            }
            save(tTextView);
            textViewIdMapInitCommandList.put(tTextView.getId(), initCommandList);
        });
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                tCommandService.saveCommandList("TEXTVIEW", "init", textViewIdMapInitCommandList);
            }
        };
        new Thread(runnable).start();
    }

    @Autowired
    private TCommandService tCommandService;


    @Override
    public void deleteTextViewsByPageId(Integer pageId) {
        List<TTextView> list = lambdaQuery()
                .select(TTextView::getId)
                .eq(TTextView::getPageId, pageId)
                .list();
        Set<Integer> textViewIds = list.stream().map(TTextView::getId).collect(Collectors.toSet());
        QueryWrapper<TTextView> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(TTextView::getPageId, pageId);
        remove(deleteWrapper);
        tCommandService.delCommandsByMain(textViewIds, "TEXTVIEW");
    }

    @Override
    public List<TTextView> getTextViewsByPageId(Integer pageId, Double pageWidth, Double pageHeight, Double aimPageWidth, Double aimPageHeight, Boolean display) throws JsonProcessingException {
        List<TTextView> tTextViews = lambdaQuery()
                .eq(TTextView::getPageId, pageId)
                .list();
        for (TTextView tTextView : tTextViews) {
            if (!display) {
                String logicGraphData = tTextView.getLogicGraphData();
                if (!StringUtils.isEmpty(logicGraphData)) {
                    ObjectMapper mapper = new ObjectMapper();
                    Map map = mapper.readValue(logicGraphData, Map.class);
                    tTextView.setLogicGraph(map);
                }
                List<TCommand> initCommands = tCommandService.getCommandListByMain(tTextView.getId(), tTextView.getType(), "init");
                initCommands = tCommandService.fillTCommands(initCommands);
                tTextView.setInitCommandList(initCommands);
            }
            if (aimPageHeight != -1 && aimPageWidth != -1) {
                Double sourceTextViewWidth = tTextView.getW();
                tTextView.setW(Math.floor((tTextView.getW() * aimPageWidth) / pageWidth));
                tTextView.setH(Math.floor((tTextView.getH() * aimPageHeight) / pageHeight));
                tTextView.setX(Math.floor((tTextView.getX() * aimPageWidth) / pageWidth));
                tTextView.setY(Math.floor((tTextView.getY() * aimPageHeight) / pageHeight));
                tTextView.setFontSize((int) Math.floor((tTextView.getFontSize() * tTextView.getW()) / sourceTextViewWidth));
            }
            tTextView.setConditionShow(tTextView.getConditionShowData() == null ? false : tTextView.getConditionShowData() == 1);
        }
        return tTextViews;
    }

    @Override
    public List<TTextView> getTextViewIdsByPageId(Integer pageId) {
        List<TTextView> list = lambdaQuery()
                .select(TTextView::getId)
                .eq(TTextView::getPageId, pageId)
                .list();
        return list;
    }
}
